package com.link.auth.core.filter;

import com.link.auth.core.interceptors.MyInterceptor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter(filterName = "aFilter", urlPatterns = "*")
public class AFilter implements Filter {

    private static final Logger logger = LogManager.getLogger(AFilter.class);

    @Resource
    private Environment environment;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String thirdName = request.getParameter("thirdName");
        String thirdPasswd = request.getParameter("thirdPasswd");
        String openId = request.getParameter("openId");
        String thirdType = request.getParameter("thirdType");
        String corpId = request.getParameter("corpId");
        String scope = request.getParameter("scope");
        MyInterceptor.getScopeThread().set(scope);
        if (!StringUtils.isEmpty(thirdName) && !StringUtils.isEmpty(thirdPasswd)) {
            //如果传入的的第三方信息不为空，校验是否统一
            String wThirdName = environment.getProperty("appThirdLogin.userName");
            String wThirdPasswd = environment.getProperty("appThirdLogin.passwd");

            if (thirdName.equals(wThirdName) && thirdPasswd.equals(wThirdPasswd)) {
                MyInterceptor.getThirdLoginFlag().set("Y");

                if ("oauth_token".equals(thirdType)) {
                    // 认证登录
                } else if (!StringUtils.isEmpty(openId)) {
                    //如果当前为微信小程序
                    MyInterceptor.getOpenId().set(openId);
                    MyInterceptor.getThirdType().set(thirdType);
                    if (StringUtils.isEmpty(corpId)) {
                        throw new IllegalArgumentException("corpId不能为空");
                    }
                    MyInterceptor.getCorpId().set(Long.valueOf(corpId));
                }
            } else {
                MyInterceptor.getThirdLoginFlag().set("N");
            }
        } else {
            MyInterceptor.getThirdLoginFlag().set("N");
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

}
